package com.udhtu.ii.lab1;

import static com.udhtu.ii.lab1.Function.*;

/**
 * метод золотого сечения
 */
public class GoldSequenceMethod {
    public static final double GOLDEN_CONSTANT = (1 + Math.sqrt(5)) / 2;
    private double epsilon;
    private double left;
    private double right;
    private int count;

    GoldSequenceMethod() {
        epsilon = EPSILON;
        left = LEFT;
        right = RIGHT;
    }

    private double goldSequenceMethod(int goal) {
        double x1, x2, f1, f2;
        count=0;
        left = LEFT;
        right = RIGHT;
        while (Math.abs(right - left) > epsilon) {
            count++;
            x1 = right - ((right - left) / GOLDEN_CONSTANT);
            x2 = left + ((right - left) / GOLDEN_CONSTANT);
            f1 = function(x1);
            f2 = function(x2);

            if (f1 >= f2 * goal)
                left = x1;
            else right = x2;
        }

        return function((left + right) / 2);
    }

    public void compute() {

        System.out.println("Метод золотого сечения:");
        System.out.println("min=" + goldSequenceMethod(MIN));
        System.out.println("max=" + goldSequenceMethod(MAX));
        System.out.println("count="+count);

    }
}
